package com.zlx.sharelive.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.zlx.module_base.base_api.res_data.BaseInfoBean;
import com.zlx.module_base.base_api.res_data.QueryByBean;
import com.zlx.module_base.base_api.res_data.VideoWatchBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_fg.BaseFg;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.activity.LoginAc;
import com.zlx.sharelive.activity.MemberAc;
import com.zlx.sharelive.activity.ShortVideoDetailsAc;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.StringUt;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.bzcoder.mediapicker.cameralibrary.util.ScreenUtils;

/**
 * 观影记录——短视频
 */
public class ViewingShortVideoFg extends BaseFg {

    @BindView(R.id.sw_layout)
    SwipeRefreshLayout sw_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    private BaseInfoBean mBaseInfoBean;
    private int videoCount;
    private String type = "2";
    private int page = 1;
    private List<VideoWatchBean.InfoDTO.RecordsDTO> mList = new ArrayList<>();
    private CommonRecyclerViewAdapter<VideoWatchBean.InfoDTO.RecordsDTO> mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fg_viewing_short_video;
    }

    @Override
    protected void initViews() {
        super.initViews();

        initRecyclerView();
        getVideoWatch(page);
        queryById();
        getBaseInfo();

        sw_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getVideoWatch(page);
                mAdapter.loadMoreComplete(false);
            }
        });
    }

    /**
     * 用户基本信息
     */
    private void getBaseInfo() {
        ApiUtil.getUserApi().getBaseInfo(SPUtil.getToken(getContext())).
                observe(getViewLifecycleOwner(), new BaseObserver<>(
                        new BaseObserverCallBack<ApiResponse<BaseInfoBean>>() {
                            @Override
                            public void onSuccess(ApiResponse<BaseInfoBean> data) {
                                if (null != data) {
                                    if (null != data.getData()) {
                                        if (null != data.getData().getInfo()) {
                                            mBaseInfoBean = data.getData();
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();

                            }
                        }));
    }

    /**
     * 根据用户id查询个人信息
     */
    private void queryById() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(getContext()), (String) SPUtil.get(getContext(), Constants.SP_ID, ""))
                .observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
                    @Override
                    public void onSuccess(ApiResponse<QueryByBean> data) {
                        if (null != data) {
                            if (null != data.getData()) {
                                if (null != data.getData().getInfo()) {
                                    if (data.getData().getInfo().size() > 0) {
                                        if (null != data.getData().getInfo().get(0).getResult()) {
                                            if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getVideoCount())) {
                                                videoCount = Integer.valueOf(data.getData().getInfo().get(0).getResult().getVideoCount());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                }));
    }

    /**
     * 观影记录
     */
    private void getVideoWatch(int page) {
        ApiUtil.getVideoApi().getVideoWatch(SPUtil.getToken(getContext()),
                type, String.valueOf(page)).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<VideoWatchBean>>() {
            @Override
            public void onSuccess(ApiResponse<VideoWatchBean> data) {
                sw_layout.setRefreshing(false);
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    if (null != data.getData().getInfo().get(0).getRecords()) {
                                        List<VideoWatchBean.InfoDTO.RecordsDTO> list = new ArrayList<>();
                                        list.addAll(data.getData().getInfo().get(0).getRecords());
                                        if (page == 1) {
                                            mAdapter.refreshDatas(list, true);
                                        } else {
                                            mAdapter.refreshDatas(list, false);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    /**
     * 初始化列表
     */
    private void initRecyclerView() {
        rv_data.setLayoutManager(new GridLayoutManager(getContext(), 2));

        mAdapter = new CommonRecyclerViewAdapter<VideoWatchBean.InfoDTO.RecordsDTO>(getContext(), mList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, VideoWatchBean.InfoDTO.RecordsDTO entity, int position) {
                GlideImgManager.glideLoader(getContext(), entity.getVideo(), holder.getView(R.id.iv_short_video_image), 1);
                holder.setText(R.id.tv_like_count, entity.getLikeCount());
                if (entity.getIsLike().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_like_count)).setImageResource(R.mipmap.fabulous_img_true);
                } else {
                    ((ImageView) holder.getView(R.id.iv_like_count)).setImageResource(R.mipmap.fabulous_img_false);
                }
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_short_video;
            }
        };

        rv_data.setAdapter(mAdapter);

        mAdapter.setLoadMore(true);

        mAdapter.setOnLoadMoreListener(new CommonRecyclerViewAdapter.OnLoadMoreListener() {
            @Override
            public void onloadmore() {
                ++page;
                getVideoWatch(page);
            }
        });

        mAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                //先判断是否登录
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    //免费还有次数
                    if (videoCount > 0) {
                        startActivity(new Intent(getContext(),
                                ShortVideoDetailsAc.class)
                                .putExtra("id", mList.get(position).getId())
                                .putExtra("video", mList.get(position).getVideo()));
                    } else {
                        //没有免费次数 弹出充值会员
                        dialogMember();
                    }
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
            }
        });
    }

    private void dialogMember() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getContext(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getContext(), R.layout.dialog_home_member, null);
        dialog.setContentView(view);

        TextView tv_video_count = view.findViewById(R.id.tv_video_count);
        tv_video_count.setText(videoCount + "");

        Button bt_member = view.findViewById(R.id.bt_member);

        bt_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), MemberAc.class)
                        .putExtra("data", mBaseInfoBean));
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    //改变bitmap尺寸的方法
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }
}
